package com.xixilala.ndkdemo

import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.graphics.drawable.BitmapDrawable
import android.os.Bundle
import android.os.Environment
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*
import java.io.File
import java.nio.ByteBuffer
import kotlin.experimental.and


fun log(str:String) {
    Log.d("ndk","--$str--")
}

class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        sample_text.text = stringFromJNI()

        btnPlus.setOnClickListener {
            val p0 = etPN0.text.toString().toInt()
            val p1 = etPN1.text.toString().toInt()
            tvPR.text = calPlus(p0,p1).toString()
        }
        btnLog.setOnClickListener {
            printLog()
        }
        btnUseTime.setOnClickListener {
            val bm = BitmapFactory.decodeResource(resources,R.mipmap.p0)
            val w = bm.width
            val h = bm.height
            val pixels  = IntArray(w*h)

            //参考 https://www.cnblogs.com/mingfeng002/p/6542652.html
            //一行一行的读
            bm.getPixels(pixels,0,w,0,0,w,h)

            val res = funUseTime(pixels, w, h)
            val resBm = Bitmap.createBitmap(w,h,Bitmap.Config.RGB_565)
            resBm.setPixels(res,0,w,0,0,w,h)
            ivProcess.setImageBitmap(resBm)
        }

        btnShowFiles.setOnClickListener {
            val downloadPath = Environment.getExternalStorageDirectory().absolutePath + File.separator + Environment.DIRECTORY_DOWNLOADS
            log("----- srcPath=${downloadPath}")
            showThePathFiles(downloadPath)
        }

        btnGrayImage.setOnClickListener {
            val current = System.currentTimeMillis()
            val bm = convertGrayImg(R.mipmap.p0)
            val now = System.currentTimeMillis()
            log("java process image use ${(now-current)}")
            ivProcess.setImageBitmap(bm)
        }
        btnProcessBitmapInfo.setOnClickListener { getBitmapInfo() }

        val dynamicNDKRegister = DynamicNDKRegister()
        btnDynamicReg.setOnClickListener { log("result = ${dynamicNDKRegister.dynamicFun(1,2)}") }
        val commonNDKRegister = CommonRegister()
        btnCommonReg.setOnClickListener { log("result = ${commonNDKRegister.printLog("123 java ")}") }
        btnCommonApiCall.setOnClickListener { someCommonApiCall() }
    }

    /**
     * A native method that is implemented by the 'native-lib' native library,
     * which is packaged with this application.
     */
    private external fun stringFromJNI(): String

    private external fun calPlus(p1:Int, p2:Int):Int

    private external fun printLog()

    private external fun funUseTime(imageBytes: IntArray,bmWidth :Int,bmHeight:Int):IntArray

    private external fun showThePathFiles(filePath:String?)

    private external fun getBitmapInfoC(bm:Bitmap)

    private external fun someCommonApiCall()


    private fun getBitmapInfo() {
        val w = 1
        val h = 1

        val bm = Bitmap.createBitmap(w,h,Bitmap.Config.ARGB_8888)
        bm.eraseColor(Color.parseColor("#FF992266"))
        val bytes = ByteArray(w*h*4)
        val dst = ByteBuffer.wrap(bytes)
        bm.copyPixelsToBuffer(dst)
        log("BMINFO JAVA R=${Integer.toHexString((bytes[0].toInt() and 0xff))}")
        log("BMINFO JAVA G=${Integer.toHexString((bytes[1].toInt()  and 0xff))}")
        log("BMINFO JAVA B=${Integer.toHexString((bytes[2].toInt()  and 0xff))}")
        log("BMINFO JAVA A=${Integer.toHexString((bytes[3].toInt()  and 0xff))}")

        getBitmapInfoC(bm)

    }

    private fun convertGrayImg(resID: Int): Bitmap? {
        val img1 = (resources.getDrawable(resID) as BitmapDrawable).bitmap
        val w = img1.width
        val h = img1.height
        val pix = IntArray(w * h)
        img1.getPixels(pix, 0, w, 0, 0, w, h)
        val alpha = 0xFF shl 24
        for (i in 0 until h) {
            for (j in 0 until w) {
                // 获得像素的颜色
                var color = pix[w * i + j]
                val red = color and 0x00FF0000 shr 16
                val green = color and 0x0000FF00 shr 8
                val blue = color and 0x000000FF
                color = (red + green + blue) / 3
                color = alpha or (color shl 16) or (color shl 8) or color
                pix[w * i + j] = color
            }
        }
        val result = Bitmap.createBitmap(w, h, Bitmap.Config.RGB_565)
        result.setPixels(pix, 0, w, 0, 0, w, h)
        return result
    }


    companion object {
        // Used to load the 'native-lib' library on application startup.
        init {
            System.loadLibrary("native-lib")
        }
    }
}

